/*
 * @Author: 噜噜噜 1163376226@qq.com
 * @Date: 2025-03-31 10:31:51
 * @LastEditors: 噜噜噜 1163376226@qq.com
 * @LastEditTime: 2025-04-21 17:10:17
 * @FilePath: /auto/automation-project/js/module.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import apiConfig from "./apiConfig.js";

// 初始化新增模块表单
async function initAddModuleForm() {
  try {
    // 获取并显示模块列表
    const modulesResponse = await fetch(apiConfig.getURL("modules", "list"), {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });
    if (!modulesResponse.ok) {
      const errorText = await modulesResponse.text();
      throw new Error(`请求失败: ${modulesResponse.status} - ${errorText}`);
    }

    const responseData = await modulesResponse.json();
    const modules = responseData || [];
    const moduleListEl = document.getElementById("moduleList");
    const itemTemplate = document.getElementById("moduleItemTemplate");
    const noDataTemplate = document.getElementById("noDataTemplate");

    if (!moduleListEl || !itemTemplate || !noDataTemplate) {
      throw new Error("未找到所需DOM元素");
    }

    // 清空列表
    moduleListEl.innerHTML = "";

    if (modules.length > 0) {
      modules.forEach((module) => {
        const clone = itemTemplate.content.cloneNode(true);
        const nameSpan = clone.querySelector(".module-name");
        nameSpan.textContent = `${module.modulesName}` || "未命名模块";
        nameSpan.style.fontWeight = "bold";
        nameSpan.style.color = "#333";
        moduleListEl.appendChild(clone);
      });
    } else {
      const clone = noDataTemplate.content.cloneNode(true);
      moduleListEl.appendChild(clone);
    }
  } catch (error) {
    console.error("初始化模块表单失败:", error);
    alert("初始化错误: " + error.message);
  }
}

// 新增模块页面初始化逻辑
document.addEventListener("DOMContentLoaded", async () => {
  const form = document.getElementById("addModuleForm");
  if (!form) return;

  try {
    await initAddModuleForm();

    form.addEventListener("submit", async (e) => {
      e.preventDefault();

      try {
        const formData = {
          moduleName: e.target.elements.moduleName.value,
          description: e.target.elements.moduleDescription.value,
        };

        const response = await fetch(apiConfig.getURL("modules", "create"), {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(formData),
        });

        const result = await response.json();
        if (result.code !== 200)
          throw new Error(result.msg || `提交失败: ${response.status}`);
        alert(result.msg || "新增模块成功！");
        e.target.reset();
        await initAddModuleForm();
      } catch (error) {
        console.error("表单提交失败:", error);
        alert(`操作失败: ${error.message}`);
      }
    });
  } catch (error) {
    console.error("页面初始化失败:", error);
    alert(`初始化错误: ${error.message}`);
  }
});
